<template>
  <div class="dealer-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>经销商管理</span>
        </div>
      </template>
      
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="经销商名称">
          <el-input v-model="queryParams.dealerName" placeholder="请输入经销商名称" clearable />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="queryParams.address" placeholder="请输入地址" clearable />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="queryParams.contactPerson" placeholder="请输入联系人" clearable />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb-2">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="dealerList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userId" label="用户ID" width="80" align="center" />
        <el-table-column prop="dealerName" label="经销商名称" width="180" show-overflow-tooltip />
        <el-table-column prop="address" label="地址" width="200" show-overflow-tooltip />
        
        <el-table-column label="Logo" width="100" align="center">
          <template #default="scope">
            <el-image 
              v-if="scope.row.logo" 
              :src="scope.row.logo" 
              :preview-src-list="[scope.row.logo]"
              style="width: 50px; height: 50px"
              fit="cover"
            />
            <span v-else>无Logo</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="contactPerson" label="联系人" width="120" />
        <el-table-column prop="contactPhone" label="联系电话" width="140" />
        <el-table-column prop="businessLicense" label="营业执照" width="120" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip />
        
        <el-table-column label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 添加/编辑经销商对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      append-to-body
    >
      <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model.number="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="经销商名称" prop="dealerName">
          <el-input v-model="form.dealerName" placeholder="请输入经销商名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicense">
          <el-input v-model="form.businessLicense" placeholder="请输入营业执照编号" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="Logo" prop="logo">
          <el-input v-model="form.logo" placeholder="请输入Logo图片URL" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" rows="4" placeholder="请输入经销商描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看经销商对话框 -->
    <el-dialog
      title="经销商详情"
      v-model="viewDialogVisible"
      width="700px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="经销商ID">{{ viewForm.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ viewForm.userId }}</el-descriptions-item>
        <el-descriptions-item label="经销商名称">{{ viewForm.dealerName }}</el-descriptions-item>
        <el-descriptions-item label="营业执照">{{ viewForm.businessLicense }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ viewForm.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ viewForm.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDate(viewForm.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{ formatDate(viewForm.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ viewForm.address }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ viewForm.description }}</el-descriptions-item>
        <el-descriptions-item label="Logo" :span="2">
          <el-image 
            v-if="viewForm.logo" 
            :src="viewForm.logo" 
            :preview-src-list="[viewForm.logo]"
            style="width: 100px; height: 100px"
            fit="cover"
          />
          <span v-else>无Logo</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAllDealers, 
  getDealersByPage,
  addDealer, 
  updateDealer, 
  deleteDealer,
  searchDealers
} from '@/api/dealer'
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue'

const loading = ref(false)
const dealerList = ref([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('添加经销商')
const isEdit = ref(false)
const selectedIds = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dealerName: '',
  address: '',
  contactPerson: '',
  contactPhone: ''
})

// 表单数据
const form = ref({
  id: undefined,
  userId: '',
  dealerName: '',
  address: '',
  businessLicense: '',
  contactPerson: '',
  contactPhone: '',
  logo: '',
  description: ''
})

// 查看表单数据
const viewForm = ref({
  id: '',
  userId: '',
  dealerName: '',
  address: '',
  businessLicense: '',
  contactPerson: '',
  contactPhone: '',
  logo: '',
  description: '',
  createTime: '',
  updateTime: ''
})

// 表单规则
const rules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', message: '用户ID必须为数字', trigger: 'blur', transform: val => Number(val) }
  ],
  dealerName: [
    { required: true, message: '请输入经销商名称', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  businessLicense: [
    { required: true, message: '请输入营业执照', trigger: 'blur' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 获取经销商列表
const getList = async () => {
  loading.value = true
  try {
    // 如果有查询条件，使用搜索接口
    if (hasQueryCondition()) {
      const params = {
        dealerName: queryParams.dealerName || undefined,
        address: queryParams.address || undefined,
        contactPerson: queryParams.contactPerson || undefined,
        contactPhone: queryParams.contactPhone || undefined
      }
      const response = await searchDealers(params)
      dealerList.value = response || []
      total.value = dealerList.value.length
    } else {
      // 否则使用分页接口
      const response = await getDealersByPage(queryParams.pageNum, queryParams.pageSize)
      dealerList.value = response.data || []
      total.value = response.total || 0
    }
  } catch (error) {
    console.error('获取经销商列表失败:', error)
    ElMessage.error('获取经销商列表失败')
  } finally {
    loading.value = false
  }
}

// 判断是否有查询条件
const hasQueryCondition = () => {
  return queryParams.dealerName || 
         queryParams.address || 
         queryParams.contactPerson || 
         queryParams.contactPhone
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.dealerName = ''
  queryParams.address = ''
  queryParams.contactPerson = ''
  queryParams.contactPhone = ''
  handleQuery()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 表格选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加经销商'
  form.value = {
    id: undefined,
    userId: '',
    dealerName: '',
    address: '',
    businessLicense: '',
    contactPerson: '',
    contactPhone: '',
    logo: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑经销商'
  form.value = { ...row }
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  viewForm.value = { ...row }
  viewDialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该经销商吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDealer(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条经销商记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 批量删除目前需要循环调用单个删除API
      const promises = selectedIds.value.map(id => deleteDealer(id))
      await Promise.all(promises)
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  const formRef = ref(null)
  
  try {
    if (isEdit.value) {
      await updateDealer(form.value)
      ElMessage.success('更新成功')
    } else {
      await addDealer(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.dealer-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-2 {
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 